package com.google.androidcamp.session4.data;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DBAdapter {
    public static final String KEY_ID = "_id";
    public static final String KEY_NOTETEXT = "note_text";
    
    private static final String DATABASE_NAME = "elephant_text.db";
    private static final String NOTES_TABLE = "notes";
    private static final int DATABASE_VERSION = 1;
    
    private SQLiteDatabase mDb;
    private DBHelper mDBHelper;
    private final Context mContext;
    
    public DBAdapter(Context context) {
        this.mContext = context;
        this.mDBHelper = new DBHelper(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    
    // Open the database.
    public void open() throws SQLiteException {
        mDb = mDBHelper.getWritableDatabase();
    }
    
    // Close the database.
    public void close() throws SQLiteException {
        mDb.close();
    }
    
    public long saveNote(ContentValues noteValues) throws SQLiteException {
        long updatedRows = mDb.update(NOTES_TABLE, noteValues, null, null);
        if (updatedRows == 0) {
            return mDb.insert(NOTES_TABLE, null, noteValues);
        }
        return updatedRows;
    }
    
    public Cursor getNote() {
        return mDb.query(NOTES_TABLE,
                         new String[] {KEY_ID, KEY_NOTETEXT},
                         null,
                         null,
                         null,
                         null,
                         null);
    }
    
    private static class DBHelper extends SQLiteOpenHelper {
        private static final String DATABASE_CREATE = 
            String.format("create table %s (%s integer primary key autoincrement, %s text not null);",
                NOTES_TABLE, KEY_ID, KEY_NOTETEXT);
        
        public DBHelper(Context context, String name, CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w("DBAdapter", String.format("Upgrading from version %d to %d. All old data will be gone!",
                oldVersion, newVersion));
            // Drop the old table.
            db.execSQL(String.format("drop table if exists %s", DATABASE_NAME));
            // Create a new one.
            onCreate(db);
        }
    }
}
